#ifndef XLCOMM_BASE_CONDITIONLATCH_H_
#define XLCOMM_BASE_CONDITIONLATCH_H_

#include <condition_variable>
#include <mutex>

#include "xlcomm/define.h"
#include "xlcomm/noncopyable.h"

namespace xlcomm {

// 不同线程间等待条件满足/等待任务完成
class XLCOMM_API ConditionLatch : noncopyable {
 public:
  explicit ConditionLatch();

  // 阻塞等待条件满足，如果条件已满足则立即返回
  void Wait();

  // 置为条件已满足并通知一次
  inline void SetAndNotifyOnce() {
    if (!finish_) {
      std::lock_guard<std::mutex> lock(mutex_);
      finish_ = true;
      condition_.notify_all();
    }
  }

 private:
  mutable std::mutex mutex_;
  std::condition_variable condition_;
  bool finish_;
};

}  // namespace xlcomm

#endif  // XLCOMM_BASE_CONDITIONLATCH_H_